import { defaultQuestionConfig } from '../config/questionConfig'
import { cloneDeep as _cloneDeep, map as _map } from 'lodash-es'
import { QUESTION_TYPE } from '@/common/typeEnum.ts'
const generateQuestionField = () => {
  const num = Math.floor(Math.random() * 1000)
  return `data${num}`
}

export function getRandom(len) {
  return Math.random()
    .toString()
    .slice(len && typeof len === 'number' ? 0 - len : -6)
}

const generateHash = (hashList) => {
  let hash = getRandom()
  let isExistsHash = hashList.includes(hash)

  while (isExistsHash) {
    hash = getRandom()
    isExistsHash = hashList.includes(hash)
  }
  return hash
}

function getOptions(type) {
  const options = [].concat({ ..._cloneDeep(defaultQuestionConfig) }.options)
  if (type === QUESTION_TYPE.BINARY_CHOICE) {
    options[0].text = '对'
    options[1].text = '错'
  }
  return options
}

export const getNewField = (fields) => {
  let field = generateQuestionField()
  let isFieldExists = fields.includes(field)

  while (isFieldExists) {
    field = generateQuestionField()
    isFieldExists = fields.includes(field)
  }
  return field
}

export const getQuestionByType = (type, fields) => {
  // console.log('getQuestionByType', type, fields)
  const newQuestion = _cloneDeep(defaultQuestionConfig)
  newQuestion.type = type
  newQuestion.field = getNewField(fields)
  newQuestion.options = getOptions(type)
  const hashList = []
  for (const option of newQuestion.options) {
    const hash = generateHash(hashList)
    hashList.push(hash)
    option.hash = hash
  }

  // console.log('newQuestion', newQuestion)
  return newQuestion
}

export function filterQuestionPreviewData(data, currentEditOne = '') {
  let indexNumber = 1
// console.log('render', data)
  return _map(data, (item, index) => {
    const preType = item.type

    const newData = {
      ...item,
      isSelected: index === currentEditOne,
      indexNumber: 0,
      qIndex: index
    }
    // 根据是否展示序号，处理 indexNumber
    if (newData.showIndex) {
      newData.indexNumber = indexNumber
      indexNumber++
    }

    // 处理选项的方向
    newData.layout = /-v/.test(preType) ? 'vertical' : newData.layout

    return newData
  })
}

// 将数组转换为树形结构
export function arrayToTree (array, id = 'id', parentId = 'parentId', children = 'children') {
  const result = []
  const map = {}

  array.forEach(item => {
    map[item[id]] = item
  })

  array.forEach(item => {
    const parent = map[item[parentId]]
    if (parent) {
      (parent[children] || (parent[children] = []))
        .push(item)
    } else {
      result.push(item)
    }
  })

  return result
}

// 判断两个数组是否有交集
export function hasIntersection (arr1, arr2) {
  return arr1.some(element => arr2.includes(element));
}

/**
 * @description 使用递归扁平化菜单，方便添加动态路由
 * @param {Array} menuList 菜单列表
 * @returns {Array}
 */
export function getFlatMenuList(menuList) {
  let newMenuList = JSON.parse(JSON.stringify(menuList));
  return newMenuList.flatMap(item => [item, ...(item.children ? getFlatMenuList(item.children) : [])]);
}

/**
 * @description 使用递归过滤出需要渲染在左侧菜单的列表 (需剔除 isHide == true 的菜单)
 * @param {Array} menuList 菜单列表
 * @returns {Array}
 * */
export function getShowMenuList(menuList) {
  let newMenuList = JSON.parse(JSON.stringify(menuList));
  return newMenuList.filter(item => {
    item.children?.length && (item.children = getShowMenuList(item.children));
    return !item.meta?.isHide;
  });
}
/**
 * @description 使用递归找出所有面包屑存储到 pinia/vuex 中
 * @param {Array} menuList 菜单列表
 * @param {Array} parent 父级菜单
 * @param {Object} result 处理后的结果
 * @returns {Object}
 */
export const getAllBreadcrumbList = (menuList, parent = [], result = {}) => {
  for (const item of menuList) {
    result[item.path] = [...parent, item];
    if (item.children) getAllBreadcrumbList(item.children, result[item.path], result);
  }
  return result;
};